import baseUrl from './config.js'
import common from "./login.js"

function request(url, method, data, header) {
	uni.showLoading({
		title: '加载中...'
	})
	return new Promise((resolve, reject) => {
		if (method == 'POST') {
			let Authorization = uni.getStorageSync('Authorization')
			header = {
				'content-type': "application/x-www-form-urlencoded",
				'Authorization': "Wechat " + Authorization
			}
		}
		uni.request({
			url: baseUrl + url,
			method: method,
			data: data,
			header: header,
			success: function(resp) {
				uni.hideLoading();
				if (resp.data.code == 0) {
					resolve(resp)
				} else {
					reject(resp)
				}
			},
			fail: function(resp) {
				uni.hideLoading();
				reject(resp);
			},
		})
	})
}



let requestB = (url, method, data, header = {}) => {
	uni.showLoading({
		title: '加载中...'
	})
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			method: method,
			data: data,
			header: header,
			success: function(resp) {
				// debugger
				setTimeout(function() {
					uni.hideLoading();
				}, 500);
				// 需要自定义逻辑的接口，直接返回
				let needCustomUrls = ['/edu/classCourseChange/getClassAndWeekDayIndex'];
				if (needCustomUrls.includes(url)) {
					resolve(resp.data)
					return;
				}
				if (resp.data.code == 0) {
					console.log(url);
					console.log(resp.data);
					resolve(resp.data)
				} else {
					if (resp.data.code == 999998) {
						// token失效,跳转到微信授权页
						uni.reLaunch({
							url: '/pagesLogin/loginRegister/wxLogin'
						})
						return;
					}
					if (resp.data.code == 999995) {
						// 未绑定，跳转到绑定页
						uni.reLaunch({
							url: '/pagesLogin/loginRegister/bindAccount'
						})
						return;
					}
					uni.showToast({
						title: resp.data.message,
						icon: "none"
					})
					let obj = {
						errMsg: resp.data.message
					}
					reject(obj)
				}
			},
			fail: function(resp) {
				uni.hideLoading();
				uni.showToast({
					title: resp.errMsg,
					icon: "none"
				})
				reject(resp);
			},
		})

	})


}
// 封装get方法
function get(obj) {
	let header = ""
	if (!obj.header) {
		let Authorization = uni.getStorageSync('Authorization')
		header = {
			'Authorization': "Wechat " + Authorization
		}
	}
	return requestB(obj.url, 'GET', obj.data, header)
}
// 封装post方法
let post = (obj) => {
	let Authorization = uni.getStorageSync('Authorization')
	let header = {
		'Authorization': "Wechat " + Authorization
	}
	header['content-type'] = obj.header ? obj.header['content-type'] : 'application/x-www-form-urlencoded';

	return requestB(obj.url, 'POST', obj.data, header)
}

export default {
	request,
	get,
	post
}
